/*
 * @Descripttion: 本地存储，附加功能：自定义定时清空
 * @version: 
 * @Author: spring
 * @Date: 2022-04-17 11:54:31
 * @LastEditors: spring
 * @LastEditTime: 2022-04-17 14:46:15
 */
import {
  GStoragePix
} from './global';

interface StorageInterFace {
  /**
   * 设置本地离线缓存
   * @param {string} name  名称
   * @param {any}    value 数据
   * @param {number} time  有效期
   */
  setItem(name: string, value: any, time?: number): void;

  /**
   * 获取本地缓存
   * @param  {string} name [description]
   * @return {string}      [description]
   */
  getItem(name: string): string;

  /**
   * 移除本地缓存
   * @param {string} name [description]
   */
  removeItem(name: string): void;
}

class Storage implements StorageInterFace {
  setItem(name: string, value: any, time?: number): void {
    localStorage.setItem(name, value);

    if (time) {
      let timestamp: number = Date.parse(new Date().toString());
      timestamp = timestamp / 1000 + time;
      localStorage.setItem(name + GStoragePix, timestamp.toString());
    }
  }

  getItem(name: string): string {
    const deadtime: number = parseInt(localStorage.getItem(name + GStoragePix) || '');

    if (deadtime && deadtime !== NaN && deadtime > 0) {
      if (deadtime < Date.parse(new Date().toString()) / 1000) {
        this.removeItem(name);
      }
    }

    return localStorage.getItem(name) || '';
  }

  removeItem(name: string): void {
    localStorage.removeItem(name);
    localStorage.removeItem(name + GStoragePix);
  }
}

export default new Storage();
